package com.life.ai.server.framework.cron;

import cn.hutool.cron.CronUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

/**
 * SysJobListener
 * 定时任务监听器，系统启动时将定时任务启动
 *
 * @author kylewka
 * @since 2025/1/6
 */
@Slf4j
@Configuration
@SuppressWarnings("all")
public class CronJobListener implements ApplicationListener<ApplicationStartedEvent>, Ordered {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        SpringUtil.getBean(CronJobInterface.class).loadCronJobs()
                .forEach(cronJob -> CronUtil.schedule(cronJob.getId(), cronJob.getCronExpression(), () -> {
                    try {
                        // 运行定时任务
                        log.info("start job {}-{} ", cronJob.getId(), cronJob.getJobName());
                        JobInvokeUtil.invokeMethod(cronJob);
                        log.info("finsh job {}-{} ", cronJob.getId(), cronJob.getJobName());
                    } catch (Exception e) {
                        log.error("job {}-{} run error,{}", cronJob.getId(), cronJob.getJobName(), e.getMessage(), e);
                    }

                }));
        // 设置秒级别的启用
        CronUtil.setMatchSecond(true);
        // 启动定时器执行器
        CronUtil.restart();
    }

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }
}
